﻿using Infrastructure.Attribute;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZR.DataCollection.ICommunication;
using ZR.DataCollection.InterfaceClass;
using ZR.DataCollection.SingleParameter;
using ZR.Model.Models.ProductionControl;
using ZR.Service.IService.ProductionControl;

namespace ZR.DataCollection.Execute
{
    /// <summary>
    /// 配方监控
    /// </summary>
    [AppService(ServiceType = typeof(IExecuteWork), ServiceLifetime = LifeTime.Singleton)]
    public class ExecuteFormulaWork : IExecuteWork
    {
        private readonly NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();

        private readonly IEquipmentFormulaService _equipmentFormulaService;
        private readonly IEquipmentFormulaLogService _equipmentFormulaLogService;

        public ExecuteFormulaWork(
            IEquipmentFormulaService equipmentFormulaService,
            IEquipmentFormulaLogService equipmentFormulaLogService)
        {
            _equipmentFormulaService = equipmentFormulaService;
            _equipmentFormulaLogService = equipmentFormulaLogService;
        }

        public void ExecuteImport()
        {
            if (CurrentAppInfo.Current.InterfaceCommExtend == null)
            {
                CurrentAppInfo.Current.InterfaceCommExtend.CommunicationDataCallback += CommunicationDefault_plc_dataChange;
            }
        }

        public void CommunicationDefault_plc_dataChange(string stationType, INormCommunication communication, int itemNo, string address, object value)
        {
            if (itemNo == 12)//配方监控点位序号
            {
                switch (Convert.ToInt16(value))
                {
                    case 1://上传配方监控触发
                        UploadFormula(communication, stationType);
                        break;

                    case 0://下载配方监控触发
                        DownFormula(communication, stationType);
                        break;
                }
            }
        }

        private async void UploadFormula(INormCommunication communication, string stationType)
        {
            await Task.Run(() =>
            {
                try
                {
                    string lineCode = CurrentOPInfo.Current.WorkStationConfig.Find(f => f.WorkstationCode.Equals(stationType)).ProductionLineCode;
                    //配方读取ID
                    int formulaId = Convert.ToInt16(communication.ReadValue(1).ToString());
                    List<EquipmentFormula> equipmentFormulaList = _equipmentFormulaService.QueryByStatonAndLineAndFormula(stationType, lineCode, formulaId);
                    if (equipmentFormulaList.Any())
                    {
                        foreach (var item in equipmentFormulaList)
                        {
                            var newValue = communication.ReadAddress(item.ItemAddress);
                            item.CraftValue = newValue.ToString();
                            item.VersionNo += 1;
                            item.CreationTime = DateTime.Now;
                        }
                        _equipmentFormulaService.UpdateList(equipmentFormulaList);
                        RecordModification(equipmentFormulaList, "ToPC");
                    }
                }
                catch (Exception ex)
                {
                    logger.Error(ex, "上传配方错误");
                }
            });
        }

        public async void DownFormula(INormCommunication communication, string stationType)
        {
            await Task.Run(() =>
            {
                try
                {
                    string lineCode = CurrentOPInfo.Current.WorkStationConfig.Find(f => f.WorkstationCode.Equals(stationType)).ProductionLineCode;
                    //配方读取ID
                    int formulaId = Convert.ToInt16(communication.ReadValue(1));
                    List<EquipmentFormula> equipmentFormulaList = _equipmentFormulaService.QueryByRecipeId(formulaId);
                    if (equipmentFormulaList.Any())
                    {
                        foreach (var item in equipmentFormulaList)
                        {
                            communication.WriteAddress(item.ItemAddress, item.CraftValue);
                        }
                        RecordModification(equipmentFormulaList, "FormPC");
                    }
                }
                catch (Exception ex)
                {
                    logger.Error(ex, "下载配方错误");
                }
            });
        }

        /// <summary>
        /// 变动记录
        /// </summary>
        /// <param name="formulas"></param>
        private async void RecordModification(List<EquipmentFormula> formulas, string source)
        {
            await Task.Run(() =>
            {
                List<EquipmentFormulaLog> formulaLogs = new List<EquipmentFormulaLog>();
                foreach (var item in formulas)
                {
                    EquipmentFormulaLog formulaLog = new EquipmentFormulaLog();
                    formulaLog.ProductionLine = item.ProductionLine;
                    formulaLog.StationCode = item.StationCode;
                    formulaLog.VersionNo = item.VersionNo;
                    formulaLog.RecipeId = item.RecipeId;
                    formulaLog.RecipeName = item.RecipeName;
                    formulaLog.CraftName = item.CraftName;
                    formulaLog.CraftValue = item.CraftValue;
                    formulaLog.LogSource = source;
                    formulaLog.CreationTime = DateTime.Now;
                    formulaLog.CraftName = item.CreatorName;
                    formulaLogs.Add(formulaLog);
                }
                _equipmentFormulaLogService.InsertList(formulaLogs);
            });
        }
    }
}